<?php

use \Mapper\RefundModel as RefundMapper;
use \Mapper\OrderModel as OrderMapper;
use \Mapper\SparringBuyDetailModel as BuyDetailMapper;
use \Mapper\MemberModel as MemberMapper;

class RefundController extends \Base\AbstractController {

    public function listAction() {
        $request = $this->getRequest();
        $status  = (int)$request->get('status');
        $orderId = (int)$request->get('order_id');
        $where   = [];

        if($status > 0) {
            $where['status'] = $status;
        }

        if($orderId > 0) {
            $where['order_id'] = $orderId;
        }

        $paginator = new \Lib\Paginator('refund');
        $paginator->where($where);

        $this->assign('page', $paginator->getPage());
        $this->assign('count', $paginator->count());
        $this->assign('perPage', $paginator->getPerpage());
        $this->assign('lists', $paginator->lists());

    }

    public function editAction() {
        $request = $this->getRequest();
        $id      = (int)$request->get('id');
        $status  = (int)$request->get('status');
        $remark  = (string)trim($request->get('remark'));
        $mapper  = RefundMapper::getInstance();
        $model   = $mapper->findById($id);

        if(!$model instanceof \OrderRefundModel) {
            return false;
        }

        if($request->isPost()) {
            $model->setStatus($status);
            $model->setUpdate_time(time());
            $model->setRemark($remark);
            $errMsg = $this->validate($model);

            if($errMsg !== false) {
                return \Response::errmsg($errMsg);
            }

            try {
                $rows = $mapper->update($model, ['id' => $id]);

                if($rows > 0) {
                    return \Response::msg();
                } elseif($rows == 0) {
                    return \Response::errmsg('信息未改动!');
                }
            } catch(\Exception $e) {
                return \Response::errmsg($e->getMessage());
            }
        }

        $this->assign('model', $model);
    }

    /**
     * @desc 退款(卖家/大腿)
     *
     * @return false
     */
    public function forceAction() {
        $request = $this->getRequest();
        $orderId = (int)$request->get('order_id');

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return \Response::errmsg('无效的订单id!');
        }

        $refundMapper = RefundMapper::getInstance();

        $return = \Lib\Finance::getInstance()->flow($orderModel->getTo_uid(), \Lib\Consts::F_REFUND_SUCCESS,
            $orderModel->getPay_price(), function () use ($orderModel, $refundMapper) {

                $return = $this->changestatus($orderModel->getId(), \Lib\Consts::ORDER_STATUS_PAY,
                    \Lib\Consts::ORDER_STATUS_REFUND_FINISH);

                if(!$return) {
                    return false;
                }

                $model = new \OrderRefundModel();
                $model->setOrder_id($orderModel->getId());
                $model->setSum($orderModel->getPrice());
                $model->setReason('');
                $model->setStatus(\Lib\Consts::ORDER_REFUND_STATUS_FORCE);
                $model->setAdd_time(time());

                $id = $refundMapper->insert($model);

                if($id <= 0) {
                    return false;
                }

                $sparringNoArr   = explode(',', $orderModel->getSparring_no());
                $buyDetailMapper = BuyDetailMapper::getInstance();

                $data = [
                    'status'      => \Lib\Consts::SPARRING_DETAIL_STATUS_NORMAL,
                    'update_time' => time(),
                ];

                try {
                    $rows = $buyDetailMapper->update($data, [
                        'id'     => $sparringNoArr,
                        'status' => \Lib\Consts::SPARRING_DETAIL_STATUS_PAY,
                    ]);
                } catch(\Exception $e) {
                    $rows = 0;
                }

                if($rows <= 0) {
                    return false;
                }

                return true;
            });

        if(!$return) {
            return \Response::errmsg('订单退款失败!');
        }

        $memberMapper = MemberMapper::getInstance();
        $fromUidModel = $memberMapper->findById($orderModel->getFrom_uid());
        $toUidModel   = $memberMapper->findById($orderModel->getTo_uid());

        if(!$fromUidModel instanceof \MemberModel || !$toUidModel instanceof \MemberModel) {
            return \Response::errmsg('无效的uid');
        }

        $buyDetailMapper = BuyDetailMapper::getInstance();
        $sparringNoArr   = explode(',', $orderModel->getSparring_no());
        $detailModels    = $buyDetailMapper->fetchAll(['id' => $sparringNoArr]);

        if(empty($detailModels)) {
            return \Response::msg('强制退款成功');
        }

        $timeInterval = '';

        foreach($detailModels as $detailModel) {
            $timeInterval .=
                date('H:i', $detailModel->getBegin_time()) . '-' . date('H:i', $detailModel->getEnd_time()) . ' ';
        }

        // 大腿
        $fromData = [
            'type'        => 'sell',
            'order_no'    => $orderModel->getOrder_no(),
            'time'        => $timeInterval,
            'cancel_time' => date('m月d日 H:i', time()),
            'price'       => $orderModel->getPrice(),
        ];
        $toData   = [
            'type'        => 'buy',
            'order_no'    => $orderModel->getOrder_no(),
            'time'        => $timeInterval,
            'cancel_time' => date('m月d日 H:i', time()),
            'price'       => $orderModel->getPrice(),
        ];

        \Lib\Pay\Wechat::getInstance()->doSend($fromUidModel->getOpen_id(), \Lib\Consts::TEMP_ID_REFUND,
            'wx.dev.gaoqiapp.com/order_detail.html?order_id=' . $orderId . '&fund_flow=1', $fromData);

        \Lib\Pay\Wechat::getInstance()->doSend($toUidModel->getOpen_id(), \Lib\Consts::TEMP_ID_REFUND,
            'wx.dev.gaoqiapp.com/order_detail.html?order_id=' . $orderId . '&fund_flow=1', $toData);

        return \Response::msg('强制退款成功');
    }

    protected function changestatus($orderId, $oldStatus, $newStatus) {
        if($orderId <= 0) {
            return false;
        }

        if($oldStatus <= 0 || $oldStatus >= 10 || $newStatus <= 0 || $newStatus >= 10) {
            return false;
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return false;
        }

        if($orderModel->getStatus() !== $oldStatus) {
            return false;
        }

        $data = [
            'status'      => $newStatus,
            'update_time' => time(),
        ];

        try {
            $rows = $orderMapper->update($data, ['id' => $orderId, 'status' => $oldStatus]);
            return $rows > 0 ? true : false;
        } catch(\Exception $e) {
            return false;
        }
    }

    private function validate(\OrderRefundModel $model) {
        if(empty($model->getStatus())) {
            return '状态值不能为空';
        }

        return false;
    }

}
